<template>
  <div class="todo-header">
    <img :src="userInfo.img" alt="头像" class="avatar" />
    <input
      type="text"
      placeholder="请输入你的任务名称，按回车键确认"
      v-model="title"
      @keyup.enter="addItem"
    />
    <button @click="addItem">+</button>
  </div>
</template>

<script>
import { mapState } from "vuex"
export default {
  props: {
    addTodo: Function,
    todos: Array
  },
  data() {
    return {
      title: ""
    }
  },
  computed: {
    ...mapState(["userInfo"])
  },
  methods: {
    addItem() {
      //1. 检查输入的合法性
      const title = this.title.trim()
      if (!title) {
        this.$notify({
          title: "提示",
          message: "请输入内容",
          type: "warning",
          position: "top-right",
          duration: 0
        })
        return
      }
      // console.log(this.todos);
      for (let i = 0; i < this.todos.length; i++) {
        if (this.todos[i].title === title) {
          alert(`<${title}>已经存在`)
          return
        }
      }
      // 2. 根据输入生成一个todo对象
      const todo = {
        title: this.title,
        completed: false
      }
      // 3. 添加到todos
      //console.log(todo);
      this.addTodo(todo)
      // 4. 清除输入
      this.title = ""
    }
  }
}
</script>

<style lang="less" scoped>
.todo-header {
  display: flex;
  align-items: center;
  width: 95%;
  .avatar {
    width: 40px;
    height: 40px;
    background-color: lightblue;
    border-radius: 50%;
  }
  input {
    flex: 1;
    width: 98%;
    height: 28px;
    font-size: 14px;
    border: none;
    border-radius: 4px;
    padding: 4px 7px;
    margin: 10px 10px 10px 20px;
    background-color: #ecf0f1;
    transition: 0.3s;
  }
  input:focus {
    outline: none;
    border-color: rgba(82, 168, 236, 0.8);
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
  }
  button {
    border: none;
    font-size: 14px;
    border-radius: 4px;
    height: 36px;
    padding: 4px 12px;
    transition: 0.3s;
    color: #747d8c;
    font-size: 20px;
    font-weight: bold;
  }
  button:hover {
    color: #fff;
    background-color: rgba(255, 165, 2, 0.3);
  }
}
</style>
